<template>
  <div class="training-class-list">
    <!-- 搜索区域 -->
    <div class="search-area" v-if="showSearch">
      <el-form inline :model="searchForm" class="search-form" ref="searchForm">
        <el-form-item label="培训班编号" prop="trainingClassCode">
          <el-input v-model="searchForm.trainingClassCode" placeholder="请输入培训班编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建年份" prop="trainingYear">
          <el-select v-model="searchForm.trainingYear" placeholder="请选择创建年份" clearable>
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year"
              :value="year"
             />
          </el-select>
        </el-form-item>
        <el-form-item label="班级状态" prop="classStatus">
          <el-select v-model="searchForm.classStatus" placeholder="选择班级状态" clearable>
            <el-option
              v-for="dict in dict.type.class_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训类型" prop="signUpCategory">
          <el-select v-model="searchForm.signUpCategory" placeholder="请选择开班类型" clearable style="width:200px">
            <el-option
              v-for="dict in dict.type.bmlb"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开班时间" prop="startTimeRange">
          <el-date-picker
            v-model="searchForm.startTimeRange"
            type="daterange"
            range-separator=" - "
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy/MM/dd"
            value-format="yyyy-MM-dd"
            :clearable="true"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="培训班名称" prop="trainingClassName">
          <el-input v-model="searchForm.trainingClassName" placeholder="请输入培训班名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherName">
          <el-input v-model="searchForm.headTeacherName" placeholder="请输入班主任姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 功能按钮栏 -->
    <div class="action-buttons">
      <el-button type="default" @click="handleViewAllResult">
        <i class="el-icon-view"></i> 查看结果
      </el-button>
      <div class="action-separator"></div>
      <el-button type="default" @click="handleToggleSearch">
        <i :class="showSearch ? 'el-icon-up' : 'el-icon-down'"></i>
        {{ showSearch ? '隐藏搜索' : '显示搜索' }}
      </el-button>
      <el-button type="default" @click="handleRefresh">
        <i class="el-icon-refresh"></i> 刷新
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%;"
      v-loading="tableLoading"
      @selection-change="handleSelectionChange"
      row-hover-class="table-row-hover"
      :header-cell-style="headerCellStyle"
      empty-text="暂无培训班数据"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="trainingClassName" label="培训班名称" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="signUpCategory" label="培训类型" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bmlb"
            :value="scope.row.signUpCategory"
          />
        </template>
      </el-table-column>
      <el-table-column label="班主任" width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ formatHeadTeachers(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="培训开始日期" width="200"></el-table-column>
      <el-table-column prop="endDate" label="培训截止日期" width="200"></el-table-column>
      <el-table-column prop="trainingNum" label="培训人数" width="100" align="center"></el-table-column>
      <el-table-column prop="fillNum" label="填报人数" width="100" align="center">
        <template slot-scope="scope">
          <span :class="getReportRateClass(scope.row)">{{ scope.row.fillNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleViewResult(scope.row)" size="small">查看结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="total">共 {{ total }} 条</span>
      <el-select
        v-model="pageSize"
        @change="handlePageSizeChange"
        size="mini"
        class="page-size-select"
      >
        <el-option label="10条/页" value="10"></el-option>
        <el-option label="20条/页" value="20"></el-option>
        <el-option label="50条/页" value="50"></el-option>
      </el-select>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        size="small"
      ></el-pagination>
    </div>

    <!-- 培训报表弹窗 -->
    <el-dialog
      title="培训结果报表"
      :visible.sync="reportDialogVisible"
      width="90%"
      :fullscreen="isFullscreen"
      :close-on-click-modal="false"
      @close="handleReportDialogClose"
      append-to-body
    >
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>培训结果报表</span>
          <el-button
            type="text"
            @click="isFullscreen = !isFullscreen"
            :icon="isFullscreen ? 'el-icon-exit-fullscreen' : 'el-icon-full-screen'"
          ></el-button>
        </div>
      </template>

      <!-- 引入子组件 -->
      <satisfaction-survey
        :class-id="currentClassId"
        :visible="reportDialogVisible"
        @update:visible="handleReportVisibleChange"
      ></satisfaction-survey>
    </el-dialog>
  </div>
</template>

<script>
import { trainingClassList } from "@/api/training/TrainingClass";
// 导入子组件
import satisfactionSurvey from '@/views/training/class/TrainingClass/satisfactionSurvey.vue';

export default {
  name: 'classQuestionnaireSurvey',
  // 注册子组件
  components: {
    satisfactionSurvey
  },
  dicts: ["bmlb", "class_status"],
  data() {
    return {
      showSearch: true,
      searchForm: {
        trainingClassCode: '',
        trainingYear: '',
        classStatus: '',
        startTimeRange: [],
        trainingClassName: '',
        headTeacherName: '',
        signUpCategory: ''
      },
      tableData: [],
      yearOptions: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      searchLoading: false,
      selectedRows: [],

      // 弹窗相关状态
      reportDialogVisible: false, // 报表弹窗显示状态
      currentClassId: '', // 当前选中的班级ID
      isFullscreen: false // 弹窗是否全屏
    };
  },
  computed: {
    headerCellStyle() {
      return {
        'background-color': '#f5f7fa',
        'font-weight': 'bold',
        'text-align': 'center',
        'padding': '12px 0'
      };
    }
  },
  created() {
    const currentYear = new Date().getFullYear();
    this.yearOptions = Array.from({ length: 10 }, (_, i) => currentYear - i);
    this.fetchTableData();
  },
  methods: {
    // 搜索处理
    handleSearch() {
      if (this.searchForm.startTimeRange && this.searchForm.startTimeRange.length === 2) {
        const [start, end] = this.searchForm.startTimeRange;
        if (new Date(start) > new Date(end)) {
          this.$message.error('开始日期不能晚于结束日期');
          return;
        }
      }

      this.searchLoading = true;
      this.currentPage = 1;
      this.fetchTableData().finally(() => {
        this.searchLoading = false;
      });
    },

    // 重置搜索
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.startTimeRange = [];
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 切换搜索区域显示
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },

    // 刷新数据
    handleRefresh() {
      this.fetchTableData();
    },

    // 查看单个结果 - 打开弹窗
    handleViewResult(row) {
      if (!row.trainingClassId) {
        this.$message.error('数据异常，无法查看结果');
        return;
      }
      this.currentClassId = row.trainingClassId;
      this.reportDialogVisible = true;
    },

    // 查看全部结果（批量查看）
    handleViewAllResult() {
      if (this.selectedRows.length > 0) {
        if (this.selectedRows.length === 1) {
          // 单个选中时直接打开
          this.currentClassId = this.selectedRows[0].trainingClassId;
          this.reportDialogVisible = true;
        } else {
          // 多个选中时提示
          this.$message.warning('暂支持单个班级查看结果，请选择一个班级');
        }
      } else {
        this.$message.warning('请先选择需要查看的培训班');
      }
    },

    // 获取搜索参数
    getSearchParams() {
      return {
        trainingClassCode: this.searchForm.trainingClassCode.trim(),
        trainingYear: this.searchForm.trainingYear,
        classStatus: this.searchForm.classStatus,
        signUpCategory: this.searchForm.signUpCategory,
        trainingClassName: this.searchForm.trainingClassName.trim(),
        headTeacherName: this.searchForm.headTeacherName.trim(),
        startTime: this.searchForm.startTimeRange?.[0] || '',
        endTime: this.searchForm.startTimeRange?.[1] || '',
        pageSize: this.pageSize,
        currentPage: this.currentPage
      };
    },

    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        const params = this.getSearchParams();
        const res = await trainingClassList(this.addDateRange(params, params.startTimeRange));

        if (res.code === 200) {
          this.tableData = res.rows || [];
          this.total = res.total || 0;
        } else {
          this.$message.error(res.msg || '获取数据失败');
          this.tableData = [];
          this.total = 0;
        }
      } catch (error) {
        console.error('获取培训班数据失败:', error);
        this.$message.error('网络异常，获取数据失败');
        this.tableData = [];
        this.total = 0;
      } finally {
        this.tableLoading = false;
      }
    },

    // 分页大小变更
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData();
    },

    // 当前页变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },

    // 选择行变更
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    },

    // 格式化班主任显示
    formatHeadTeachers(row) {
      const teachers = [];
      if (row.headTeacher1Name) teachers.push(row.headTeacher1Name);
      if (row.headTeacher2Name) teachers.push(row.headTeacher2Name);
      return teachers.length > 0 ? row.headTeacher1Name : '未设置';
    },

    // 获取填报率样式
    getReportRateClass(row) {
      if (row.trainingNum === 0) return 'text-default';
      const rate = row.fillNum / row.trainingNum;
      if (rate < 0.3) return 'text-danger';
      if (rate < 0.7) return 'text-warning';
      return 'text-success';
    },

    // 处理报表弹窗关闭
    handleReportDialogClose() {
      this.reportDialogVisible = false;
      this.currentClassId = '';
      this.isFullscreen = false;
    },

    // 接收子组件的显示状态变更
    handleReportVisibleChange(visible) {
      this.reportDialogVisible = visible;
      if (!visible) {
        this.currentClassId = '';
        this.isFullscreen = false;
      }
    }
  }
};
</script>

<style scoped>
.training-class-list {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

/* 搜索区域样式 */
.search-area {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-form .el-form-item {
  margin-bottom: 10px !important;
}

.search-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
  padding-right: 8px;
}

.search-form .el-input,
.search-form .el-select,
.search-form .el-date-picker {
  width: 200px;
}

/* 按钮区域样式 */
.action-buttons {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px 0;
}

.action-separator {
  width: 1px;
  height: 24px;
  background-color: #e4e7ed;
  margin: 0 5px;
}

/* 表格样式 */
::v-deep .el-table {
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
}

::v-deep .el-table td {
  border-bottom: 1px solid #f2f2f2;
}

::v-deep .table-row-hover {
  background-color: #f0f7ff !important;
}

::v-deep .el-table__empty-text {
  padding: 60px 0;
  color: #909399;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
  gap: 15px;
}

.total {
  color: #606266;
  font-size: 14px;
  margin-right: 5px;
}

.page-size-select {
  width: auto !important;
}

::v-deep .el-pagination {
  margin: 0;
}

/* 状态文本样式 */
.text-danger {
  color: #f56c6c;
  font-weight: 500;
}

.text-warning {
  color: #e6a23c;
  font-weight: 500;
}

.text-success {
  color: #67c23a;
  font-weight: 500;
}

.text-default {
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-form {
    gap: 10px;
  }

  .search-form .el-input,
  .search-form .el-select,
  .search-form .el-date-picker {
    width: 180px;
  }

  .action-buttons {
    gap: 8px;
  }
}

@media (max-width: 992px) {
  .search-form .el-input,
  .search-form .el-select,
  .search-form .el-date-picker {
    width: 150px;
  }
}

@media (max-width: 768px) {
  .training-class-list {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-form .el-input,
  .search-form .el-select,
  .search-form .el-date-picker {
    width: 100%;
  }

  .pagination {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
